#include "LoginSignUp.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include "Object.h"
#include "Object.h"
#include "Scene.h"
Player p(0, 0, "", "", 0, 0, 0, 0, 0); // 初始化全局玩家对象
  

using namespace std;


/* 登录界面打印 */
void Login::show()
{
    
    system("clear");
    cout<<endl;
    cout << "正在显示登录界面.." << endl;
    sleep(1);
    system("clear");
    cout<<endl;
    cout << "正在显示登录界面......" << endl;
    sleep(1);
    system("clear");
    
    while(1)
    {
        string UserName;
        string Passwd;
        cout<<endl;
        cout << "=======================登录界面=======================\n";
        cout <<endl;
        cout << "          请输入账号名称：";
        cin >> UserName;
        cout <<endl;
        cout << "          请输入密码：";
        cin >> Passwd;
        cout << "======================================================\n";
        if(login(UserName, Passwd) == true)
        {
            cout<<endl;
            cout << "正在进入游戏……(๑•̀ㅂ•́)و✧" << endl;
            cout << "又是元气满满打怪兽的一天！！！" << endl;
            sleep(1);
            system("clear");
            Player player(0, 0, UserName, "👧", 100, 40, 1, 0, 100);
            p = player;         // 将玩家对象赋值给全局玩家对象
            DataShow(p);
            system("clear");
            break;
        }

        cin.ignore();                   
        sleep(1);
        Screen::getInstance().show();   
        break;
    }
}

void Login::PlayGame(Player &p)
{
    Scene s(p);
    s.InitMonsters();     //初始化怪兽
    s.InitTreasureBox();  //初始化宝箱 

    while(1)                                //死循环
    {
        system("clear");
        s.show();
        p.show();
        p.Move(s);
        
        Monster * m = s.IsPosEqual();   //获得要战斗的怪兽
        if(m)                           //m不为空则战斗
        {
            s.Fight(m);
            s.SaveGame();
        }
        TreasureBox * t = s.TIsPosEqual();
        if(t)
        {
            s.OpenBox(t);
            s.SaveGame();
        }
        system("clear"); //清屏
    }

}

/* 读取UserList */
Login::Login()
{
    std::ifstream f("./存档/user.txt", ios::in); // 打开，只读
    if (!f.is_open())
    {
        std::cout << "用户文件打开失败！\n";
        exit(-1);   //退出程序
    }

    std::string line;
    while (getline(f, line))
    {
        istringstream iss(line); // 文件输入流： 按照空格分隔读出来     还可以用fscanf
        string UserName;
        string Passwd;
        iss >> UserName >> Passwd;
        UserList[UserName] = Passwd;
    }
    f.close();
    //!这里暂时不需要输出
    // for (auto &ite : UserList)
    // {
    //     cout << ite.first << " " << ite.second << std::endl;
    // }
}

/* 登录账号 */
bool Login::login(CStrRef UserName, CStrRef Passwd)
{
    /* 重新读取一遍，解决userlist没有更新的问题 */
    std::ifstream f("./存档/user.txt", ios::in); // 打开，只读
    if (!f.is_open())
    {
        std::cout << "用户文件打开失败！\n";
        exit(-1);   //退出程序
    }

    std::string line;
    while (getline(f, line))
    {
        istringstream iss(line); // 文件输入流： 按照空格分隔读出来     还可以用fscanf
        string UserName;
        string Passwd;
        iss >> UserName >> Passwd;
        UserList[UserName] = Passwd;
    }
    f.close();

    auto ite = UserList.find(UserName);
    if(ite == UserList.end())           //没找到
    {
        std::cout<<"账号不存在！<(＿　＿)>\n";
        sleep(1);
        return false;
    }
    if(ite->second == Passwd)           //second第二个成员
    {
        std::cout<<"登录成功！O(∩_∩)O\n";
        sleep(1);
        return true;
    }
    else
    {
        std::cout<<"密码输入错误！\n";
        return false;
    }
}

/* 删除账号：删除之后重新储存 */
void Login::RemoveUser(CStrRef UserName)
{
    auto ite = UserList.find(UserName);
    if(ite != UserList.end())
    {
        UserList.erase(ite);
    }
    Save();
}

/* 修改密码 */
void Login::ChangPasswd(CStrRef UserName,CStrRef Passwd)
{
    auto ite = UserList.find(UserName);
    if(ite != UserList.end())       //找到账号
    {
        ite->second = Passwd;       //修改密码
    }
    Save();
}

/* 修改后储存：打开文件依次写入 */
void Login::Save()
{
    std::ofstream f("./存档/user.txt",std::ios::out);
    if (!f.is_open())
    {
        std::cout << "用户文件打开失败！\n";
        exit(-1);
    }

    for(auto &ite : UserList)
    {
        f<<ite.first<<" "<<ite.second<<std::endl;
    }
    f.close();
}

void Login::DataShow(Player &p)
{
    system("clear");
    cout << endl;
    cout << "============登录成功！欢迎来到魔塔世界🎮=============\n";
    cout << "||                                                ||\n";
    cout << "||                  1、新的游戏                   ||\n";
    cout << "||                                                ||\n";
    cout << "||                  2、读取游戏                   ||\n";
    cout << "||                                                ||\n";
    cout << "||                  3、退出登录                   ||\n";
    cout << "||                                                ||\n";
    cout << "====================================================\n";

    cout<< "请选择你的操作：";
    char c = 0;
    cin >> c;
    if(c == '1')
    {
        PlayGame(p);
    }
    else if(c == '2')
    {
        string UserName;
        string Passwd;
        system("clear");
        cout <<endl;
        cout << "=======================读档界面=======================\n";
        cout <<endl;
        cout << "          请输入账号名称：";
        cin >> UserName;
        cout <<endl;
        cout << "          请输入密码：";
        cin >> Passwd;
        cout << "======================================================\n";
        if(login(UserName, Passwd) == true)
        {
            cout<<endl;
            std::string PlayerDataPath = "./存档/" + UserName;
            Scene s(p);
            s.LoadGame(UserName, p);
           
            while(1)                                //死循环
            {
                system("clear");
                s.show();
                p.show();
                p.Move(s);
                
                Monster * m = s.IsPosEqual();   //获得要战斗的怪兽
                if(m)                           //m不为空则战斗
                {
                    s.Fight(m);
                    s.SaveGame();
                }
                TreasureBox * t = s.TIsPosEqual();
                if(t)
                {
                    s.OpenBox(t);
                    s.SaveGame();
                }
                system("clear"); //清屏
            }
                std::cout << "游戏数据加载成功！" << std::endl;
                
                //PlayGame(p);
            
            // else
            // {
            //     std::cout << "游戏数据加载失败！" << std::endl;
            // }
        }
        else if(login(UserName, Passwd) == false)
        {
            std::cout << "账号或密码错误！登录失败。" << std::endl;
        }
    }
    else if(c == '3')
    {
        // SaveGameData(p);
        // cout << "玩家数据已保存！\n";
        // cout << "感谢游玩魔塔世界，再见！" << endl;
        // sleep(1);
        cout << "确定退出登录？ y or n？\n";
        char c;
        cin >> c;
        if(c == 'y')
        {
            sleep(1);
            Screen::getInstance().show();   // 返回主页面
        }
        else if(c == 'n')
        {
            DataShow(p);
        }
        else
        {
            cout << " 无效操作，请重新输入：" << endl;
        }
        
    }
    else
    {
        cout << " 无效操作，请重新输入：" << endl;
    }
}

/* 注册账号 */
void SignUp::show()
{
    system("clear");
    cout<<endl;
    cout << "正在显示注册界面.." << endl;
    sleep(1);
    system("clear");
    cout<<endl;
    cout << "正在显示注册界面......" << endl;
    sleep(1);
    system("clear");

    string UserName;
    string Passwd;
    cout << endl;
    cout << "=======================注册界面=======================\n";
    cout << endl;
    cout << "          请输入账号名称：";
    cin >> UserName;
    cout << endl;
    cout << "          请输入密码：";
    cin >> Passwd;
    cout << "======================================================\n";
    
    Login login;
    if (login.GetUserList().find(UserName) != login.GetUserList().end()) 
    {
        cout << "账号已存在！ 注册失败！\n";
        sleep(1);
    }
    else 
    {
        // 保存到文件
        Save(UserName, Passwd, "./存档/user.txt");
        
        // 更新内存中的 UserList
        login.GetUserList()[UserName] = Passwd;
        cout << "注册成功！按Enter键返回主页面。" << endl;
        cin.ignore();                   // 清除缓冲区
        cin.get();                      // 等待用户按下任意键继续
        
    }
    Screen::getInstance().show();   // 返回主页面
}


/* 注册时储存 */
void SignUp::Save(CStrRef UserName, CStrRef passwd, CStrRef filePath)
{
    /* 追加写入 */
    //打开文件
    std::ofstream f(filePath, std::ios::app);               
    if (!f.is_open())
    {
        std::cout << " 文件打开失败！保存账号密码失败！\n";
        return;
    }
    //打开成功，账号写入文件中
    f << UserName << " " << passwd << std::endl;
    //关闭文件
    f.close();
}

/* 构造：创建文件夹 */
Screen::Screen()
{
    // string userName = SignUp::GetUserName(p);
    // string cmd = "mkdir ./存档" + userName;
    string cmd = "mkdir ./存档";
    system(cmd.c_str());
    // system(std::string(cmd + "/存档一：人物属性").c_str());
    // system(std::string(cmd + "/存档二：怪兽数据").c_str());
    // system(std::string(cmd + "/存档三：宝箱数据").c_str());
    string cmd1 = "touch ./存档/user.txt";
    system(cmd1.c_str());
    faceList[1] = new Login; 
    faceList[2] = new SignUp;
}
Screen::~Screen() 
{
    delete faceList[1];
    delete faceList[2];   
}

void Screen::show()
{
    system("clear");
    printf("\033[47;30m\n");
    cout << "=================欢迎来到魔塔世界🎮=================\n";
    cout << "||                                                ||\n";
    cout << "||                  1、登录游戏                   ||\n";
    cout << "||                                                ||\n";
    cout << "||                  2、注册账号                   ||\n";
    cout << "||                                                ||\n";
    cout << "||                  3、退出游戏                   ||\n";
    cout << "||                                                ||\n";
    cout << "====================================================\n";

    cout<< "请选择你的操作：";
    char c = 0;
    cin >> c;

    /* 状态注册机：策略模式 */
    if(c >= '1' && c <= '2')
    {
        faceList[c - '0']->show();
    }
    else if(c == '3')
    {
        cout << "感谢游玩魔塔世界，再见！" << endl;
        sleep(1);
        exit(-1);
    }
    else
    {
        cout << " 无效操作，请重新输入：" << endl;
    }
}


